import modelExtend from 'dva-model-extend'

export const model = {
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
  },
}

export const pageModel = modelExtend(model, {
  state: {
    options: {},
    list: [],
    pagination: {
      showSizeChanger: true,
      showQuickJumper: true,
      current: 1,
      total: 0,
      pageSize: 20,
    },
  },

  reducers: {
    querySuccess(state, { payload }) {
      const { list, pagination } = payload
      return {
        ...state,
        list,
        pagination: {
          ...state.pagination,
          ...pagination,
        },
      }
    },
    //请求选项合并
    queryOptions(state, { payload }) {
      return {
        ...state,
        options: {
          ...state.options,
          ...payload
        }
      }
    },

    //服务器端返回 value/label 选项
    queryOptionValueLabel(state, { payload }) {
      let options = {};
      //处理keyvalue数据
      Object.keys(payload).forEach((key) => {
        let tmpOption = [];
        for(const k in payload[key]) {
          let item = payload[key][k]
          tmpOption[item.value] = item.label;
        }
        options[key] = tmpOption;
      })

      return {
        ...state,
        options: {
          ...state.options,
          ...options
        },
        optionValueLabel: {
          ...state.optionValueLabel,
          ...payload
        }
      }
    },
    //查询tree选项成功
    querySuccessTree(state, { payload }) {
      return {
        ...state,
        trees: {
          ...state.trees,
          ...payload
        }
      }
    },
  },
})
